/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package at.tugraz.hidipic.web.taglib;

import at.tugraz.hidipic.model.ConfigurationObject;
import at.tugraz.hidipic.web.util.annotation.FormElement;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

/**
 *
 * @author mario
 */
public class DynamicConfigForm extends TagSupport {

    private ConfigurationObject value;

    public void setValue(ConfigurationObject value) {
        this.value = value;
    }

    @Override
    public int doStartTag() throws JspException {
        JspWriter out = pageContext.getOut();
        try {
            Class beanClass = value.getClass();
            for (Field f : getAnnotatedFields(beanClass, FormElement.class)) {
                FormElement fe = f.getAnnotation(FormElement.class);
                f.setAccessible(true);
                out.print("<div class=\"control-group\">"
                        + "<label class=\"control-label\">" + fe.fieldName() + ":</label>"
                        + "<div class=\"controls\">");
                out.println("<input type=\"text\" name=\"" + f.getName() + "\" />");
                out.print("</div></div>");
            }
        } catch (Exception ex) {
            throw new JspException(ex);
        }
        return SKIP_BODY;
    }

    private List<Field> getAnnotatedFields(Class clazz, Class annotation) {
        ArrayList<Field> fields = new ArrayList<Field>();
        for (Field f : clazz.getDeclaredFields()) {
            if (f.getAnnotation(annotation) != null) {
                fields.add(f);
            }
        }
        return fields;
    }
}
